<template>
  <view class="login_outer">
    <beginOuterBox>
      <view slot="begintopImg">
        <image class="begin_title_img" src="@/static/begin/begintop.png" v-if="isShowLogo"></image>
      </view>
      <view slot="hellow">登录!</view>
      <view slot="titleText">Login～</view>
      <!-- 登录页 -->
      <view class="login_content_btnbox" slot="content">
        <!-- <view class="login_content_btnbox_tabs">
          <circleTabs
            v-model="tabIndex"
            :tabList="list"
            mode="skew"
          ></circleTabs>
        </view> -->
        <u--form labelPosition="left" ref="uForm" :model="loginData">
          <u-form-item ref="item1" prop="phone">
            <view class="login_content_phone">
              <view class="login_content_phone_img">
                <image src="@/static/login/phone.png"></image>
              </view>
              <u--input border="none" placeholder="请您输入手机号" v-model="loginData.phone" @blur="isShowLogo = true"
                @focus="isShowLogo = false">
              </u--input>
            </view>
          </u-form-item>
          <u-form-item ref="item2" v-if="tabIndex == 1">
            <view class="login_content_verification">
              <view class="login_content_verification_ipu">
                <view class="login_content_verification_img">
                  <image src="@/static/login/verification.png"></image>
                </view>
                <u--input border="none" placeholder="请输入手机验证码" v-model="phoneVerification" @blur="isShowLogo = true"
                  @focus="isShowLogo = false">
                </u--input>
              </view>
              <view class="login_content_verification_uToast">
                <u-toast ref="uToast"></u-toast>
                <u-code :seconds="seconds" startText="获取" changeText="x秒" @end="end" @start="start" ref="uCode"
                  @change="codeChange"></u-code>
                <view class="login_content_verification_uToast_btn" @click="getCanvasVerification">{{ tips }}</view>
              </view>
            </view>
          </u-form-item>
          <u-form-item ref="item3" v-if="tabIndex == 0">
            <view class="login_content_phone pawsword">
              <view class="login_content_phone_img">
                <image src="@/static/login/password.png"></image>
              </view>
              <u--input border="none" placeholder="请输入密码" v-model="password" :type="isShowPassword ? 'text' : 'password'"
                @blur="isShowLogo = true" @focus="isShowLogo = false">
                <view slot="suffix" @click="isShowPassword = !isShowPassword" style="margin-right: 20rpx">
                  <u-icon name="eye-fill" v-if="isShowPassword"></u-icon>
                  <u-icon name="eye-off" v-else></u-icon>
                </view>
              </u--input>
            </view>
          </u-form-item>
          <u-form-item ref="item3" v-if="tabIndex == 2">
            <view class="login_content_phone pawsword">
              <view class="login_content_phone_img">
                <image src="@/static/login/password.png"></image>
              </view>
              <u--input border="none" type="text" placeholder="请输入密钥" v-model="superPassword"></u--input>
            </view>
          </u-form-item>
          <u-form-item ref="item4">
            <view class="login_content_forget">
              <view class="login_content_forget_hign" @click="tabIndex = 1" v-if="tabIndex == 0 || tabIndex == 2">
                <text>短信验证码登录</text>
              </view>
              <view class="login_content_forget_hign" @click="tabIndex = 0" v-if="tabIndex == 1 || tabIndex == 2">
                <text>密码登录</text>
              </view>
              <view class="login_content_forget_hign" @click="tabIndex = 2" v-if="tabIndex == 1 || tabIndex == 0">
                <text>密钥登录</text>
              </view>
            </view>
          </u-form-item>
          <u-form-item ref="item5">
            <view class="login_content_verification_affirm">
              <view @click="getLoginUser">
                <text>确定</text>
              </view>
            </view>
          </u-form-item>
        </u--form>
        <u-popup :show="isShowVerificationImgUrl" mode="center" round="30" :closeOnClickOverlay="true"
          @close="isShowVerificationImgUrl = false">
          <view class="verification_box">
            <view class="verificationImg" @click="getCanvasVerification">
              <image :src="verificationImgUrl.encode"></image>
            </view>
            <view class="verificationIpt">
              <view>
                <u--input border="none" placeholder="请输入图形验证码" v-model="sendVerificationCode">
                </u--input>
              </view>
            </view>
            <view class="verificationIpt_affirm">
              <view @click="reqSendNoteCode">
                <text>确定</text>
              </view>
            </view>
          </view>
        </u-popup>
      </view>
    </beginOuterBox>
  </view>
</template>

<script>
import beginOuterBox from "@/components/beginOuterBox.vue";
import circleTabs from "@/components/circle-tabs/circle-tabs.vue";
import { reqLoginUser, phoneVerificationLogin, validCodeLogin } from "@/api/login.js";
import { reqCanvasVerification, reqSendNoteCode } from "@/api/all.js";

import { mapMutations, mapState } from "vuex";
export default {
  data() {
    return {
      tips: "",
      seconds: 60,
      tabIndex: 1,
      list: [
        {
          id: 0,
          title: "手机密码登录",
        },
        {
          id: 1,
          title: "手机验证码登录",
        },
      ],
      // 人机验证码
      verificationImgUrl: {},
      // 是否展示人机验证码
      isShowVerificationImgUrl: false,
      // 人机验证码
      sendVerificationCode: "",
      // 是否能发送验证码
      isSendVerificationCode: true,
      // 登录参数
      loginData: {
        phone: "",
        agree: 1,
      },
      // 密码登录方式
      password: "",
      // 验证码方式
      // 手机号格式是否正确
      phoneFormat: false,
      isShowPassword: false,
      phoneVerification: '',
      isShowLogo: true,
      superPassword: '',
      // rules: {
      //   // 字段名称
      //   phone: [
      //     {
      //       required: true,
      //       message: "请输入手机号",
      //       trigger: ["change", "blur"],
      //     },
      //     {
      //       // 自定义验证函数，见上说明
      //       validator: (rule, value, callback) => {
      //         // 上面有说，返回true表示校验通过，返回false表示不通过
      //         // uni.$u.test.mobile()就是返回true或者false的
      //         this.phoneFormat = uni.$u.test.mobile(value);
      //         return uni.$u.test.mobile(value);
      //       },
      //       message: "手机号码不正确",
      //       // 触发器可以同时用blur和change
      //       trigger: ["change", "blur"],
      //     },
      //   ],
      // },
    };
  },
  methods: {
    ...mapMutations(["setUserInfoSync"]),
    //获取人机校验码
    getCanvasVerification: _.throttle(async function () {
      if (!uni.$u.test.mobile(this.loginData.phone)) {
        uni.showToast({
          title: "手机号格式不正确",
          icon: "error",
        });
        return;
      }
      if (!this.isSendVerificationCode) {
        uni.showToast({
          title: "倒计时结束再发送",
          icon: "error",
        });
        return;
      }
      const result = await reqCanvasVerification();
      if (result.code == 200) {
        this.verificationImgUrl = result.data;
        this.isShowVerificationImgUrl = true;
      } else {
        uni.showToast({
          title: result.msg,
          icon: "error",
        });
      }
    }, 500),
    //发送短信
    async reqSendNoteCode() {
      if (!this.sendVerificationCode) {
        uni.showToast({
          title: "请输入图形验证码",
          icon: "error",
        });
      } else {
        const sendData = {
          phone: this.loginData.phone,
          captchaId: this.verificationImgUrl.id,
          captcha: this.sendVerificationCode,
          scenes: 2,
        };
        const result = await reqSendNoteCode(sendData);
        if (result.code == 200) {
          uni.showToast({
            title: "短信验证码发送成功",
            icon: "success",
          });
          this.getCode();
          this.isShowVerificationImgUrl = false;
        } else {
          uni.showToast({
            title: result.msg,
            icon: "error",
          });
          this.getCanvasVerification();
        }
      }
    },
    codeChange(text) {
      this.tips = text;
    },
    getCode() {
      if (this.$refs.uCode.canGetCode) {
        // 模拟向后端请求验证码
        uni.showLoading({
          title: "正在获取验证码",
        });
        setTimeout(() => {
          uni.hideLoading();
          // 这里此提示会被this.start()方法中的提示覆盖
          uni.$u.toast("验证码已发送");
          // 通知验证码组件内部开始倒计时
          this.$refs.uCode.start();
        }, 2000);
      } else {
        uni.$u.toast("倒计时结束后再发送");
      }
    },
    start() {
      this.isSendVerificationCode = false;
    },
    end() {
      this.isSendVerificationCode = true;
    },
    //  登录
    getLoginUser: _.throttle(async function () {
      if (this.tabIndex == 0) {
        if (!this.loginData.phone || !this.password) {
          uni.showToast({
            title: "手机号和密码必须填写!",
            icon: "error",
          });
          return;
        }
        // if (!uni.$u.test.mobile(this.loginData.phone)) {
        //   uni.showToast({
        //     title: "手机号格式不正确",
        //     icon: "error",
        //   });
        //   return;
        // }
        // const reg = /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9a-zA-Z]{6,20}$/;
        // if (!reg.test(this.password)) {
        //   uni.showToast({
        //     title: "密码格式为6-20位数字加字母",
        //     icon: "error",
        //   });
        //   return;
        // }
        uni.showLoading({
          title: "登录中",
        });
        const sendData = {
          ...this.loginData,
          password: this.password,
        };
        const result = await reqLoginUser(sendData);
        uni.hideLoading();
        if (result.code == 200) {
          this.setUserInfoSync(result.data);
          uni.setStorageSync("phone", this.loginData.phone);
          uni.showToast({
            title: "登录成功",
            icon: "none",
          });
          // 登陆成功去首页
          setTimeout(() => {
            uni.switchTab({
              url: "/pages/home/index",
            });
          }, 1000);
        } else {
          uni.showToast({
            title: result.msg,
            icon: "error",
          });

        }
      } else if (this.tabIndex == 1) {
        if (!this.loginData.phone || !this.phoneVerification) {
          uni.showToast({
            title: "手机号和短信验证码必须填写!",
            icon: "error",
          });
          return;
        }
        // if (!uni.$u.test.mobile(this.loginData.phone)) {
        //   uni.showToast({
        //     title: "手机号格式不正确",
        //     icon: "error",
        //   });
        //   return;
        // }
        uni.showLoading({
          title: "登录中",
        });
        const sendData = {
          ...this.loginData,
          code: this.phoneVerification,
          wxCode: uni.getStorageSync("code")
        };
        const result = await phoneVerificationLogin(sendData);
        uni.hideLoading();
        if (result.code == 200) {
          this.setUserInfoSync(result.data);
          uni.setStorageSync("phone", this.loginData.phone);
          uni.showToast({
            title: "登录成功",
            icon: "none",
          });
          // 登陆成功去首页
          setTimeout(() => {
            uni.switchTab({
              url: "/pages/home/index",
            });
          }, 1000);
        } else {
          uni.showToast({
            title: result.msg,
            icon: "error",
          });
          this.getWxCode(1)

        }
      } else if (this.tabIndex == 2) {
        if (!this.loginData.phone || !this.superPassword) {
          uni.showToast({
            title: "手机号和密钥验证码必须填写!",
            icon: "error",
          });
          return;
        }
        uni.showLoading({
          title: "登录中",
        });
        //13883059918
        const sendData = {
          ...this.loginData,
          validCode: this.superPassword,
          wxCode: uni.getStorageSync("code")
        };
        const result = await validCodeLogin(sendData);
        uni.hideLoading();
        if (result.code == 200) {
          this.setUserInfoSync(result.data);
          uni.setStorageSync("phone", this.loginData.phone);
          uni.showToast({
            title: "登录成功",
            icon: "none",
          });
          // 登陆成功去首页
          setTimeout(() => {
            uni.switchTab({
              url: "/pages/home/index",
            });
          }, 1000);
        } else {
          uni.showToast({
            title: result.msg,
            icon: "error",
          });
        }
      }
    }, 1000),

    getUrlParam(name) {
      const reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
      // const r = window.location.search.split('?')[1].match(reg);
      const r = window.location.search.split("?")[1];
      console.log(r);
      if (r) {
        const result = window.location.search
          .split("?")[1]
          .match(new RegExp("(^|&)" + "code" + "=([^&]*)(&|$)"));
        // return unescape(r[2]);
        uni.setStorageSync("code", result[2]);
        return result[2];
      }
      return null;
    },
    async getWxCode(x) {
      let appid = "wx9a11ba393646fe6d"; //公众号的APPID

      let code = this.getUrlParam("code"); //检查url中是否存在code

      let local = "https://swap.yunlegeyou.cn/#/pages/login/index"; //正式路径，即当前h5页面的路径
      // let local = "https://xckx.zhilianmanbu.com/#/pages/login/index"; //测试路径，即当前h5页面的路径

      if (code == null || code === "" || x == 1) {
        //不存在就打开下面的地址进行授权
        window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${encodeURIComponent(
          local
        )}&response_type=code&scope=snsapi_userinfo&state=1&#wechat_redirect`;
        // this.getUrlParam("code");
      } else {
        return
      }
    },
  },
  onShow() {
    clearTimeout(this.KlineTimer)
    clearInterval(this.newKlineTimer)
    this.getWxCode()
  },
  computed: {
    ...mapState(['newKlineTimer', 'KlineTimer'])
  },
  components: {
    beginOuterBox,
    circleTabs,
  },
};
</script>

<style lang="scss" scoped>
.login_outer {
  width: 100vw;
  height: 100vh;

  .begin_title_img {
    width: 126rpx;
    height: 126rpx;
    position: absolute;
    top: 62rpx;
    left: 58rpx;
  }

  .login_content_btnbox {
    z-index: 999;
    position: absolute;
    top: 142rpx;
    width: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;

    // .login_content_btnbox_tabs {
    //   width: 100%;
    //   margin-top: -160rpx;
    // }
    .login_content_phone {
      width: 545rpx;
      height: 75rpx;
      border: 3px solid #ff9e3c;
      border-radius: 26rpx;
      display: flex;
      align-items: center;
      margin-top: 60rpx;

      .login_content_phone_img {
        width: 40rpx;
        height: 40rpx;
        margin-left: 14rpx;
        margin-right: 28rpx;

        image {
          width: 100%;
          height: 100%;
        }
      }
    }

    .pawsword {
      margin-top: -10rpx;
    }

    .login_content_verification {
      width: 556rpx;
      height: 75rpx;
      display: flex;
      align-items: center;
      margin-top: -10rpx;

      .login_content_verification_ipu {
        width: 391rpx;
        height: 74rpx;
        border: 3px solid #ff9e3c;
        border-radius: 26rpx;
        display: flex;
        align-items: center;
      }

      .login_content_verification_img {
        width: 40rpx;
        height: 40rpx;
        margin-left: 14rpx;
        margin-right: 28rpx;

        image {
          width: 100%;
          height: 100%;
        }
      }

      .login_content_verification_uToast {
        width: 142rpx;
        height: 74rpx;
        background: #2f2a26;
        background: linear-gradient(to right, #666157 0%, #504c43 100%);
        border-radius: 26rpx;
        display: flex;
        justify-content: center;
        align-items: center;
        margin-left: 12rpx;

        .login_content_verification_uToast_btn {
          font-size: 31rpx;
          font-family: DreamHanSansSC;
          font-weight: normal;
          color: #fffaef;
          display: flex;
          justify-content: center;
          align-items: center;
        }
      }
    }

    .login_content_forget {
      display: flex;

      .login_content_forget_hign {
        margin-top: -20rpx;
        margin-left: 24rpx;

        text {
          font-size: 21rpx;
          font-family: Dream Han Sans SC;
          font-weight: normal;
          text-decoration: underline;
          color: #302b27;
        }
      }

      .login_content_forget_super {}
    }

    .login_content_verification_affirm {
      position: fixed;
      display: flex;
      justify-content: center;
      margin-top: 120rpx;

      view {
        width: 545rpx;
        height: 108rpx;
        background: linear-gradient(to right, #ff7007 0%, #ffa749 100%);
        border-radius: 38rpx;
        display: flex;
        justify-content: center;
        align-items: center;

        text {
          font-size: 38rpx;
          font-family: DreamHanSansSC;
          font-weight: normal;
          color: #ffffff;
        }
      }
    }
  }

  .verification_box {
    display: flex;
    flex-direction: column;
    align-items: center;
    width: 600rpx;
    height: 600rpx;

    .verificationIpt {
      width: 400rpx;
      height: 100rpx;
      border: 4rpx solid orange;
      border-radius: 38rpx;
      margin-top: 30rpx;
      display: flex;
      align-items: center;

      view {
        margin-left: 30rpx;
      }
    }

    .verificationImg {
      width: 400rpx;
      height: 200rpx;
      margin-top: 40rpx;

      image {
        width: 100%;
        height: 100%;
      }
    }

    .verificationIpt_affirm {
      display: flex;
      justify-content: center;
      margin-top: 30rpx;

      view {
        width: 400rpx;
        height: 108rpx;
        background: linear-gradient(to right, #ff7007 0%, #ffa749 100%);
        border-radius: 38rpx;
        display: flex;
        justify-content: center;
        align-items: center;

        text {
          font-size: 38rpx;
          font-family: DreamHanSansSC;
          font-weight: normal;
          color: #ffffff;
        }
      }
    }
  }
}
</style>
